import MQTT from 'mqtt'
import Vue from 'vue'
let MQTT_URL = 'ws://123.207.85.44:8083/mqtt'
const mqtt = {
  connet() {
    let time = new Date()
    time = time.getTime()
    // 连接选项
    const options = {
      // true: 清除会话, false: 保留会话
      clean: true,
      // 超时时间
      connectTimeout: 4000,
      // 认证信息
      clientId: 'test' + time,
      username: 'admin',//emqx_test4
      password: 'public'
    }
    this.ws = MQTT.connect(MQTT_URL, options)
    this.ws.on('connect', () => {
      console.log('Client connected:' + options.clientId)
      this.ws.subscribe('/device/pltest/1/altimeter/up', { qos: 2 })//高拍仪
      this.ws.subscribe('/device/pltest/+/guard/up', { qos: 2 })//门禁
      this.ws.subscribe('/device/pltest/+/envSensor/Temp/up', { qos: 0 })//温度传感器
      this.ws.subscribe('/device/pltest/+/envSensor/Humidity/up', { qos: 0 })//湿度传感器
      Vue.prototype.$mqtt = this.ws
    })
    this.ws.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })
    this.ws.on('error', (error) => {
      console.log('连接失败:', error)
    })
    this.ws.on('message', (topic, msg) => {
      if (topic != "/device/pltest/1/altimeter/up") {
        console.log('收到消息：', topic, msg.toString())
      }
      if (topic.indexOf("/altimeter/up") != -1) {
        //高拍仪-OCR识别
        window.scanContentHandle ? scanContentHandle(topic, msg) : '';
      } else if (topic.indexOf("/guard/up") != -1) {
        //门禁
        window.initUserData ? initUserData(topic, msg) : '';
      } else if (topic.indexOf("/envSensor/Temp/up") != -1) {
        //温度传感器
        window.updateTempAndHumidity ? updateTempAndHumidity(topic, msg) : '';
      } else if (topic.indexOf("/envSensor/Humidity/up") != -1) {
        //湿度传感器
        window.updateTempAndHumidity ? updateTempAndHumidity(topic, msg) : '';
      }
    })
  },
  publish() {
    let qos = 2
    let topic2 = '/device/test/COM_RW_SKCOM1:115200/rfid/continueSearch/check/down'
    let payload2 = {
      'adaptorId': 'test',
      'deviceId': 'COM_RW_SKCOM1:115200',
      'actionId': 'check',
      'start': true
    }
    this.ws.publish(topic2, JSON.stringify(payload2), qos, error => {
      if (error) {
        console.log('Publish error', error)
      }
    })
  }
}
export default mqtt
